package day_2022_7_to_8.day48;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author haomin
 * @date 2022/07/30 10:15
 **/
public class Day15_2_Num535_Encode {
    // 思路一：建立一个map，加密时存入longUrl，解密时在map中取longUrl
    public class Codec {

        private Map<Integer,String> map = new HashMap<>();
        private int id;
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            id++;
            map.put(id,longUrl);
            return "http://tinyurl.com/" + id;
        }

        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            int start = shortUrl.lastIndexOf('/')+1;
            int key = Integer.parseInt(shortUrl.substring(start));
            return map.get(key);
        }
    }

    // 思路一改进：避免id重复，使用随机数
    public class Codec2 {

        private Map<Integer,String> map = new HashMap<>();
        private Random random = new Random();
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            int key;
            while (true){
                key = random.nextInt();
                if(!map.containsKey(key)) break;
            }
            map.put(key,longUrl);
            return "http://tinyurl.com/" + key;
        }

        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            int start = shortUrl.lastIndexOf('/')+1;
            int key = Integer.parseInt(shortUrl.substring(start));
            return map.get(key);
        }
    }
}